#include "OLEDDisplay.h"
#include <WiFi.h>

// 构造函数
EnvMonitorDisplay::EnvMonitorDisplay(uint8_t address, int sda, int scl) 
    : display(address, sda, scl) {}

bool EnvMonitorDisplay::begin() {
    if(!display.init()) {
        Serial.println(F("SSD1306初始化失败"));
        return false;
    }
    display.flipScreenVertically();
    display.setFont(ArialMT_Plain_10);
    display.clear();
    return true;
}

void EnvMonitorDisplay::showSplashScreen(const String& title, const String& message) {
    display.clear();
    display.setFont(ArialMT_Plain_16);
    display.setTextAlignment(TEXT_ALIGN_CENTER);
    display.drawString(SCREEN_WIDTH/2, 10, title);
    display.setFont(ArialMT_Plain_10);
    display.drawString(SCREEN_WIDTH/2, 40, message);
    display.display();
    delay(2000);
}

// 核心更新函数
void EnvMonitorDisplay::update(float temp, int humid, float ppm,
                             bool wifiStatus, bool mqttStatus,
                             int msgID, bool humanDetected,bool lightState,bool flameDetected) {
    if(millis() - lastPageChange > PAGE_INTERVAL) {
        currentPage = (currentPage + 1) % TOTAL_PAGES;
        lastPageChange = millis();
    }
    
    display.clear();
    drawHeader(currentPage == 0 ? "环境监测" : 
              (currentPage == 1 ? "网络状态" : "人体检测"));
    
    switch(currentPage) {
        case 0: showSensorPage(temp, humid, ppm); break;
        case 1: showNetworkPage(wifiStatus, mqttStatus, msgID); break;
        case 2: showHumanPage(humanDetected); break;
        case 3: showFlamePage(flameDetected); break;
    }
    display.display();
}

// 以下是各页面实现（注意不要嵌套定义！）
void EnvMonitorDisplay::showHumanPage(bool detected) {
    display.setFont(ArialMT_Plain_24);
    display.setTextAlignment(TEXT_ALIGN_CENTER);
    display.drawString(SCREEN_WIDTH/2, 10, detected ? "有人" : "无人");
    drawHumanIcon(SCREEN_WIDTH/2 - 25, 25, detected);
    
    display.setFont(ArialMT_Plain_10);
    String hint = detected ? "检测到活动 " : "等待检测 ";
    String binaryString = String(millis() / 500 % 4, BIN);
    binaryString.replace("0", " ");
    binaryString.replace("1", "·");
    hint += binaryString;
    display.drawString(SCREEN_WIDTH/2, 55, hint);
}

void EnvMonitorDisplay::drawHumanIcon(int x, int y, bool detected) {
    if(detected) {
        display.fillCircle(x + 25, y + 10, 10);
        display.fillRect(x + 20, y + 20, 10, 20);
        display.drawLine(x + 15, y + 25, x + 35, y + 25);
        display.drawLine(x + 25, y + 40, x + 15, y + 55);
        display.drawLine(x + 25, y + 40, x + 35, y + 55);
    } else {
        display.drawTriangle(x + 25, y, x, y + 25, x + 50, y + 25);
        display.drawRect(x + 10, y + 25, 30, 30);
    }
}

void EnvMonitorDisplay::drawHeader(const String& title) {
    display.setFont(ArialMT_Plain_10);
    display.setTextAlignment(TEXT_ALIGN_LEFT);
    display.drawString(0, 0, title);
    display.setTextAlignment(TEXT_ALIGN_RIGHT);
    display.drawString(SCREEN_WIDTH, 0, String(currentPage + 1) + "/3");
    display.drawHorizontalLine(0, 12, SCREEN_WIDTH);
}

void EnvMonitorDisplay::showSensorPage(float temp, int humid, float ppm) {
    display.setFont(ArialMT_Plain_16);
    display.setTextAlignment(TEXT_ALIGN_LEFT);
    display.drawString(5, 15, String(temp, 1) + "°C");
    display.setTextAlignment(TEXT_ALIGN_RIGHT);
    display.drawString(SCREEN_WIDTH-5, 15, String(humid) + "%");
    
    display.setFont(ArialMT_Plain_10);
    display.setTextAlignment(TEXT_ALIGN_CENTER);
    display.drawString(SCREEN_WIDTH/2, 35, "MQ2: " + String(ppm, 1) + " ppm");
    display.drawHorizontalLine(0, 50, SCREEN_WIDTH);
    
    if(ppm < 0) {
        float progress = fmod(millis() / 1000.0, 3.0) / 3.0; 
        drawProgressBar(10, 55, SCREEN_WIDTH-20, 8, progress);
        display.drawString(SCREEN_WIDTH/2, 65, "校准中...");
    } else {
        float animSpeed = 0.02;
        float dynamicProgress = fmod(millis() * animSpeed, 1.0);
        float smokeLevel = min(ppm / 1000.0, 1.0);
        drawProgressBar(10, 55, SCREEN_WIDTH-20, 4, smokeLevel);
        drawProgressBar(10, 60, SCREEN_WIDTH-20, 3, dynamicProgress);
        display.drawString(SCREEN_WIDTH/2, 65, String(ppm < 1000 ? "正常" : "警告!"));
    }
}

void EnvMonitorDisplay::drawHumanIndicator(int x, int y, bool detected) {
    display.setColor(WHITE);
    display.fillCircle(x + 5, y + 5, 4);
    if(detected) {
        display.fillTriangle(x+3, y+8, x+7, y+8, x+5, y+4);
    } else {
        display.setColor(BLACK);
        display.fillCircle(x + 5, y + 5, 3);
        display.setColor(WHITE);
        display.drawHorizontalLine(x+2, y+5, 6);
    }
}

void EnvMonitorDisplay::showNetworkPage(bool wifiStatus, bool mqttStatus, int msgID) {
    drawStatusIndicator(10, 20, wifiStatus);
    display.setFont(ArialMT_Plain_10);
    display.setTextAlignment(TEXT_ALIGN_LEFT);
    display.drawString(30, 20, wifiStatus ? WiFi.SSID() : "WiFi断开");

    drawStatusIndicator(10, 35, mqttStatus);
    display.drawString(30, 35, mqttStatus ? "MQTT已连接" : "MQTT断开");

    if(wifiStatus) {
        drawWiFiSignal(WiFi.RSSI());
    }
    display.setTextAlignment(TEXT_ALIGN_RIGHT);
    display.drawString(SCREEN_WIDTH-10, 60, "#" + String(msgID));
}

void EnvMonitorDisplay::drawStatusIndicator(int x, int y, bool status) {
    display.setColor(WHITE);
    display.fillCircle(x + 5, y + 5, 4);
    if(!status) {
        display.setColor(BLACK);
        display.fillCircle(x + 5, y + 5, 3);
        display.setColor(WHITE);
    }
}

void EnvMonitorDisplay::drawWiFiSignal(int rssi) {
    int bars = map(constrain(rssi, -90, -50), -90, -50, 1, 4);
    for(int i = 0; i < 4; i++) {
        int height = (i + 1) * 4;
        display.fillRect(SCREEN_WIDTH - 25 + i * 5, 25 - height, 3, height);
    }
}

void EnvMonitorDisplay::drawProgressBar(int x, int y, int width, int height, float progress) {
    progress = constrain(progress, 0.0, 1.0);
    display.drawRect(x, y, width, height);
    display.fillRect(x + 2, y + 2, (width - 4) * progress, height - 4);
}

// 新增火焰页面显示
void EnvMonitorDisplay::showFlamePage(bool flameDetected) {
    display.setFont(ArialMT_Plain_24);
    display.setTextAlignment(TEXT_ALIGN_CENTER);
    display.drawString(SCREEN_WIDTH/2, 10, flameDetected ? "有火！" : "无火");
    drawFlameIcon(SCREEN_WIDTH/2 - 16, 30, flameDetected);
    
    display.setFont(ArialMT_Plain_10);
    display.setTextAlignment(TEXT_ALIGN_CENTER);
    display.drawString(SCREEN_WIDTH/2, 55, flameDetected ? "危险！请处理" : "环境安全");
}
// 绘制火焰图标
void EnvMonitorDisplay::drawFlameIcon(int x, int y, bool flameOn) {
    if(flameOn) {
        // 绘制火焰图标（红色）
        display.setColor(WHITE);
        display.fillTriangle(x+16, y, x+8, y+20, x+24, y+20);
        display.fillTriangle(x+16, y+5, x+12, y+25, x+20, y+25);
    } else {
        // 绘制安全图标（绿色）
        display.drawCircle(x+16, y+12, 12);
        display.drawHorizontalLine(x+16, y+8, 5);
        display.drawHorizontalLine(x+16, y+16, 5);
    }
}